import { DatePicker, message, Form } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import debounce from 'lodash/debounce';
import moment from 'moment';
import React, { PureComponent } from 'react';

import { ContentPackage, TableC, TenantC } from '@/src/components';
import { namespace } from '@/src/newModels/SystemManage/BatchManageM';

import styles from './index.less';

@connect(({ loading, BatchManageM }) => ({
  loading,
  BatchManageM,
}))
export default class BatchManage extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      columns: [
        {
          key: 'taskType',
          dataIndex: 'taskType',
          title: '任务类型',
          width: 120,
          align: 'left',
        },
        {
          key: 'applicableTenants',
          dataIndex: 'applicableTenants',
          title: '适用租户',
          width: 120,
          align: 'center',
        },
        {
          key: 'batchDate',
          dataIndex: 'batchDate',
          title: '跑批日期',
          width: 120,
          align: 'center',
        },
        {
          key: 'operate',
          dataIndex: 'operate',
          title: '操作',
          width: 120,
          align: 'right',
        },
      ],
      dataSource: [
        {
          taskType: '穿透持仓',
          key: 'SYNC',
          status: 1,
        },
        {
          taskType: '限额报表',
          status: 1,
          key: 'CALC',
        },
      ],
    };
    this.operateBatchTask = debounce(this.operateBatchTask, 500);
  }

  formRef = React.createRef();

  componentWillUnmount() {
    clearInterval(this.pollingTimer0);
    clearInterval(this.pollingTimer1);
  }

  /**
   * 操作栏
   * @param e {React.BaseSyntheticEvent}
   * @param record 行数据
   * @param index {number} 索引
   * @returns void
   */
  operateBatchTask = (e, record, index, type) => {
    e.preventDefault();
    const { dispatch } = this.props;
    const { dataSource } = this.state;
    const batchTaskType = record.key;
    const { applicableTenants, batchDate } = batchTaskType === 'SYNC' ? dataSource[0] : dataSource[1];
    if (!applicableTenants || !batchDate) return message.warning('请填写完整行数据');
    const dates = [moment(batchDate).format('YYYYMMDD')];
    if (type === 'run') {
      const copyDataSource = _.cloneDeep(this.state.dataSource);
      copyDataSource[index].status = 2;
      this.setState(
        {
          dataSource: copyDataSource,
        },
        () => {
          dispatch({
            type: `${namespace}/triggerTask`,
            payload: {
              dates,
              batchTaskType,
              tenants: applicableTenants,
            },
            callback: (taskIds) => {
              // 拿到taskIds
              const copyDataSource2 = _.cloneDeep(this.state.dataSource);
              copyDataSource2[index].status = 2;
              this.setState(
                {
                  dataSource: copyDataSource2,
                },
                () => {
                  // 开始轮询状态
                  this.pollingStatus(taskIds, index);
                },
              );
            },
          });
        },
      );
    }
    if (type === 'reset') {
      const copyDataSource = _.cloneDeep(this.state.dataSource);
      copyDataSource[index].status = 1;
      copyDataSource[index].batchDate = undefined;
      copyDataSource[index].applicableTenants = undefined;
      this.setState(
        {
          dataSource: copyDataSource,
        },
        () => {
          // 暂停轮询
          clearInterval(this[`pollingTimer${index}`]);
        },
      );
    }
  };

  /**
   * 轮询状态
   * @param taskIds {string}
   * @param index {number}
   */
  pollingStatus = (taskIds, index) => {
    const { dispatch } = this.props;
    this[`pollingTimer${index}`] = setInterval(() => {
      dispatch({
        type: `${namespace}/queryStatus`,
        payload: {
          taskIds,
        },
        callback: (data) => {
          // "data": "执行中",  或者是执行失败，执行成功
          let status = 1;
          if (data === '执行中') status = 2;
          if (data === '执行成功') status = 3;
          if (data === '执行失败') status = 4;
          const copyDataSource = _.cloneDeep(this.state.dataSource);
          copyDataSource[index].status = status;
          this.setState(
            {
              dataSource: copyDataSource,
            },
            () => {
              if ([3, 4].includes(status)) {
                // 清除定时器
                clearInterval(this[`pollingTimer${index}`]);
              }
            },
          );
        },
      });
    }, 10 * 1000);
  };

  // 按钮状态
  initText = (record, index) => {
    // 1.执行 2.执行中 3.执行成功 4.执行失败
    switch (record.status) {
      case 1:
        return (
          <a data-type='run' style={{ paddingRight: 10 }} onClick={(e) => this.operateBatchTask(e, record, index, 'run')}>
            执行
          </a>
        );
      case 2:
        return (
          <span className={styles.executing} style={{ marginRight: 10 }}>
            执行中
          </span>
        );
      case 3:
        return (
          <span className={styles.sucess} style={{ marginRight: 10 }}>
            执行成功
          </span>
        );
      case 4:
        return (
          <span className={styles.faild} style={{ marginRight: 10 }}>
            执行失败
          </span>
        );
      default:
        return null;
    }
  };

  // 修改时间
  changeBatchDate = (e, record, index) => {
    const { dataSource } = this.state;
    const copy = _.cloneDeep(dataSource);
    copy[index].batchDate = e ? moment(e) : undefined;
    this.setState({
      dataSource: copy,
    });
  };

  // 修改租户
  changeTenants = (e, record, index) => {
    const { dataSource } = this.state;
    const copy = _.cloneDeep(dataSource);
    copy[index].applicableTenants = e?.key;
    this.setState({
      dataSource: copy,
    });
  };

  // 扩展column
  enHancerColumn = (arr) => {
    arr.map((v) => {
      // 租户
      if (v.key === 'applicableTenants') {
        v.render = (text, record, index) => {
          return (
            <div className={styles.TenantCItem}>
              <TenantC
                form={this.formRef.current}
                dataIndex={`applicableTenants-${index}`}
                onChange={(e) => {
                  this.changeTenants(e, record, index);
                }}
                positionBody={true}
                initialValue={record.applicableTenants}
                multiple={true}
              />
            </div>
          );
        };
      }
      // 日期
      if (v.key === 'batchDate') {
        v.render = (text, record, index) => (
          <div>
            <DatePicker style={{ height: 30 }} value={record.batchDate} allowClear={true} onChange={(e) => this.changeBatchDate(e, record, index)} />
          </div>
        );
      }
      if (v.key === 'operate') {
        v.render = (text, record, index) => (
          <div style={{ display: 'flex', justifyContent: 'end' }}>
            {this.initText(record, index)}
            <a
              data-type='reset'
              disabled={[1, 2].includes(record.status)}
              style={[1, 2].includes(record.status) ? { cursor: 'not-allowed' } : {}}
              onClick={(e) => this.operateBatchTask(e, record, index, 'reset')}
            >
              重置
            </a>
          </div>
        );
      }
    });
    return arr;
  };

  render() {
    const { columns, dataSource } = this.state;
    const res = this.enHancerColumn(columns);
    return (
      <div>
        <ContentPackage
          title='跑批管理'
          contentHtml={
            <div className={styles.batchManagement}>
              <Form ref={this.formRef}>
                <TableC
                  columns={res || []}
                  dataSource={dataSource || []}
                  scroll={{ x: 'max-content' }}
                  rowKey='taskType'
                  bordered={true}
                  hidePage={true}
                  selfScrollY={true}
                  size='small'
                />
              </Form>
            </div>
          }
        />
      </div>
    );
  }
}
